package com.ruoyi.project.mobile.jiaqin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.R;
import com.ruoyi.project.jiaqin.downclass.domain.DownClass;
import com.ruoyi.project.jiaqin.downclass.service.IDownClassService;
import com.ruoyi.project.jiaqin.downmeasure.domain.DownMeasure;
import com.ruoyi.project.jiaqin.downmeasure.service.IDownMeasureService;
import com.ruoyi.project.jiaqin.downquotation.domain.DownQuotation;
import com.ruoyi.project.jiaqin.downquotation.service.IDownQuotationService;
import com.ruoyi.project.jiaqin.downstandard.domain.DownStandard;
import com.ruoyi.project.jiaqin.downstandard.service.IDownStandardService;
import com.ruoyi.project.jiaqin.downtrend.service.IDownTrendService;
import com.ruoyi.project.jiaqin.quotationAvaPrice.domain.QuotationDayAvaBean;
import com.ruoyi.project.jiaqin.quotationAvaPrice.domain.QuotationDayAveragePrice;
import com.ruoyi.project.jiaqin.quotationAvaPrice.service.IQuotationDayAveragePriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/jq/down")
public class ApiDownController {

    public static final String countryId = "-100";

    @Autowired
    private IDownClassService iDownClassService;
    @Autowired
    private IDownMeasureService iDownMeasureService;
    @Autowired
    private IDownStandardService iDownStandardService;
    @Autowired
    private IDownQuotationService iDownQuotationService;
    @Autowired
    private IDownTrendService iDownTrendService;
    @Autowired
    private IQuotationDayAveragePriceService iQuotationDayAveragePriceService;


    /**
     * 获取羽绒选择参数
     * @return
     */
    @GetMapping("/getDownSelectAttr")
    public R getDownSelectAttr(){
        //查分类,标准,含量
        List<DownClass> downClasses = iDownClassService.selectDownClassList(new DownClass());
        List<DownMeasure> downMeasures = iDownMeasureService.selectDownMeasureList(new DownMeasure());
        List<DownStandard> downStandards = iDownStandardService.selectDownStandardList(new DownStandard());
        JSONObject data = new JSONObject();
        data.put("downClasses",downClasses);
        data.put("downMeasures",downMeasures);
        data.put("downStandards",downStandards);
        return R.ok(data);
    }

    /**
     *  发布羽绒行情
     * @return
     */
    @PostMapping("/releaseDown")
    public R releaseDown(@RequestBody DownQuotation downQuotation){
        downQuotation.setReleaseDate(new Date());
//        //计算和上期价格  分类ID 标准ID 含绒量ID 用户ID 查上一期的价格
        DownQuotation lastDq = iDownQuotationService.selectDownQuotationByFourId(downQuotation.getMemberId()
                ,downQuotation.getDownClassId(),downQuotation.getDownMeasureId(),downQuotation.getDownStandardId());
        if(lastDq == null){
            //沒有上一期直接发布
            iDownQuotationService.insertDownQuotation(downQuotation);
            return R.ok("发布成功");
        }
        //有上一期计算上一期和本期涨跌幅
        downQuotation.setLastPrice(lastDq.getPrice());
        BigDecimal cha = downQuotation.getPrice().subtract(lastDq.getPrice());
        downQuotation.setWavePrice(cha);//计算
        //如果差值等于0
        if(cha.compareTo(new BigDecimal(0))==0){
            //昨天和今天价格相同
            downQuotation.setWavePerc(new BigDecimal(0.00));
            downQuotation.setStatus(0);
        }else if(cha.compareTo(new BigDecimal(0)) == 1){
            //昨天和今天价格不同 差大于零
            downQuotation.setWavePerc(downQuotation.getPrice()
                    .subtract(lastDq.getPrice())
                    .divide(lastDq.getPrice(),4,BigDecimal.ROUND_UP)
                    .multiply(new BigDecimal(100)));
            downQuotation.setStatus(1);
        }else{
            //差小于零
            downQuotation.setWavePerc(downQuotation.getPrice()
                    .subtract(lastDq.getPrice())
                    .divide(lastDq.getPrice(),4,BigDecimal.ROUND_UP)
                    .multiply(new BigDecimal(100)));
            downQuotation.setStatus(2);
        }
        iDownQuotationService.insertDownQuotation(downQuotation);
        return R.ok("发布成功");
    }

    @GetMapping("/getDownQuotation")
    public R getDownQuotation(@RequestParam(value="pageNum",defaultValue="1",required = false) Integer pageNum
            ,@RequestParam(value="pageSize",defaultValue="5",required = false) Integer pageSize,String downClassId,String downStandardId){
        HashMap<String, Object> map = new HashMap<>();
        DownQuotation downQuotation = new DownQuotation();
        downQuotation.setDownClassId(downClassId);
        downQuotation.setDownStandardId(downStandardId);
        PageInfo<DownQuotation> pageInfo = iDownQuotationService.selectDownQuotationListA(pageNum,pageSize,downQuotation);
        map.put("data",pageInfo);
        return R.ok(map);
    }


    /**
     * 获取羽绒走势        七天/三十天/月度 分类ID
     * @param downClassId       羽绒分类ID
     * @param downStandardId    羽绒标准ID
     * @param type          查询类型
     * @return
     */
    @GetMapping("/getDownTrend")
    public R getDownTrend(String downClassId,String downStandardId,Integer type){
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> mapp = new HashMap<>();
        List<DownMeasure> list = iDownMeasureService.selectDownMeasureList(new DownMeasure());
        if(type==1){
            //七天
            for (DownMeasure dm:list) {
                //查询趋势
                mapp.put(dm.getName(),iDownTrendService.selectDownTrendSeven(downClassId,downStandardId,dm.getId()));
            }
            map.put("data",mapp);
            return R.ok(map);
        }
        if(type==2){
            //三十天
            for (DownMeasure dm:list) {
                //查询趋势
                mapp.put(dm.getName(),iDownTrendService.selectDownTrendMonth(downClassId,downStandardId,dm.getId()));
            }
            map.put("data",mapp);
            return R.ok(map);

        }
        if(type==3){
            //月度
            return R.error("暂未开发");
        }
        return R.ok();
    }


    public QuotationDayAveragePrice getOneDayAveragePrice(DownQuotation downQuotation, Date date){
        QuotationDayAvaBean bean = new QuotationDayAvaBean();
        bean.setQuotationClassId(downQuotation.getDownClassId());
        bean.setQuotationClassAreaId("0");

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date currentDate = date;
        Calendar c = Calendar.getInstance();
        c.setTime(currentDate);
        int day1 = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day1 + 1);
        Date nextDate = c.getTime();

        bean.setStartStr(format.format(currentDate));
        bean.setEndStr(format.format(nextDate));
        bean.setStandardId(downQuotation.getDownStandardId());
        bean.setQuotationCityId(downQuotation.getCityId());
        List<QuotationDayAveragePrice> adps = iQuotationDayAveragePriceService.selectQuotationListByParams(bean);
        QuotationDayAveragePrice adp = null;
        if (adps.size() > 0){
            for (QuotationDayAveragePrice subAdp: adps) {
                adp = subAdp;
            }
        }
        return adp;
    }

    public int changeCountryData(DownQuotation downQuotation){
        downQuotation.setCityId(countryId);

        return this.changeDayAcePriceDate(downQuotation);
    }

    public int changeDayAcePriceDate(DownQuotation downQuotation){
        /*不再受用户之前是否发布限制、直接插入数据，一天只能插入一条，新的覆盖老得-----*/
        QuotationDayAveragePrice adp = this.getOneDayAveragePrice(downQuotation, new Date());

        QuotationDayAveragePrice quotationDayAveragePrice = new QuotationDayAveragePrice();
        quotationDayAveragePrice.setDate(new Date());
        quotationDayAveragePrice.setQuotationClassAreaId((long)0);
        quotationDayAveragePrice.setQuotationClassId(downQuotation.getDownClassId());

        if (adp != null) {
            BigDecimal insertPrice = downQuotation.getPrice();
            BigDecimal totlePrice = BigDecimal.valueOf(adp.getCount() * Double.parseDouble(adp.getDayAveragePrice()));
            BigDecimal count = BigDecimal.valueOf(adp.getCount() + 1);
            BigDecimal newAvaPrice = totlePrice.add(insertPrice).divide(count
                    , 2, BigDecimal.ROUND_HALF_UP);
            DecimalFormat df1 = new DecimalFormat("0.00");
            String newAvaPriceStr = df1.format(newAvaPrice);
            quotationDayAveragePrice.setDayAveragePrice(newAvaPriceStr);
            quotationDayAveragePrice.setCount(adp.getCount() + 1);
            quotationDayAveragePrice.setId(adp.getId());
            quotationDayAveragePrice.setQuotationStandardId(adp.getQuotationStandardId());
            quotationDayAveragePrice.setQuotationCityId(adp.getQuotationCityId());
            quotationDayAveragePrice.setLastDayAveragePice(adp.getLastDayAveragePice());
            return iQuotationDayAveragePriceService.updateQuotationDayAveragePrice(quotationDayAveragePrice);
        } else {
            //今日首次插入数据加入lastDayPrice
            Date currentDate = new Date();
            Calendar c = Calendar.getInstance();
            c.setTime(currentDate);
            int day1 = c.get(Calendar.DATE);
            c.set(Calendar.DATE, day1 - 1);
            Date lastDate = c.getTime();
            QuotationDayAveragePrice lastAdp = this.getOneDayAveragePrice(downQuotation, lastDate);
            if (lastAdp != null){
                quotationDayAveragePrice.setLastDayAveragePice(lastAdp.getDayAveragePrice());
            }else {
                quotationDayAveragePrice.setLastDayAveragePice("");
            }

            quotationDayAveragePrice.setCount((long) 1);
            quotationDayAveragePrice.setDayAveragePrice(downQuotation.getPrice().toString());
            quotationDayAveragePrice.setQuotationStandardId(downQuotation.getDownStandardId());
            quotationDayAveragePrice.setQuotationCityId(downQuotation.getCityId());
            return iQuotationDayAveragePriceService.insertQuotationDayAveragePrice(quotationDayAveragePrice);
        }
    }

    /**
     *  发布羽绒行情
     * @return
     */
    @PostMapping("/releaseDownLin")
    public R releaseDownLin(@RequestBody DownQuotation downQuotation){
        /*不再受用户之前是否发布限制、直接插入数据，一天只能插入一条，新的覆盖老得-----*/

        //改变cityId数据
        int i = this.changeDayAcePriceDate(downQuotation);

        //改变全国数据
        int j = this.changeCountryData(downQuotation);

        if (i == 0 || j ==0){
            return R.error("发布失败");
        }
        iDownQuotationService.insertDownQuotation(downQuotation);
        return R.ok("发布成功");

    }

    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    public static List<String> getDays(String startTime, String endTime) {

        // 返回的日期集合
        List<String> days = new ArrayList<String>();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);

            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return days;
    }

    /**
     * 获取羽绒走势        七天/三十天/月度 分类ID
     * @param downClassId       羽绒分类ID
     * @param downStandardId    羽绒标准ID
     * @param type          查询类型
     * @return
     */
    @GetMapping("/getDownTrendLin")
    public R getDownTrendLin(String downClassId,String downStandardId,Integer type,String startDay,String endDay, String cityId) throws ParseException {
        HashMap<String, Object> map = new HashMap<>();

        if (cityId.length() == 0){
            cityId = countryId;
        }

        if (type == 3) {
            //获取月度走势
//            List<>
            return R.error("暂无数据");
        }

        StringBuffer param = new StringBuffer();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        String now = df.format(new Date());
        String start = new String();
        if (type == 1){
            start = this.getPastDate(6);
        }
        if (type == 2) {
            start = this.getPastDate(29);
        }

        if (type == 4){
            start = startDay;
            now = endDay;
        }

        QuotationDayAvaBean bean = new QuotationDayAvaBean();
        bean.setStartStr(start);
        SimpleDateFormat sqlDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bean.setEndStr(sqlDf.format(new Date()));
        bean.setQuotationClassAreaId("0");
        bean.setQuotationClassId(downClassId);
        bean.setStandardId(downStandardId);
        bean.setQuotationCityId(cityId);
        //list sql结果集可能存在缺少日期的数据
        List<QuotationDayAveragePrice> list = iQuotationDayAveragePriceService.selectQuotationListByParams(bean);

        List<Object> resList = new ArrayList<>();

        Date nowDate = null;//应该存在的结果日期-结束日期
        try {
            nowDate = df.parse(now);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date startDate = null;//应该存在的结果日期-开始日期
        try {
            startDate = df.parse(start);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date tempDate = startDate; //标记日期，用于对比

        //对比日期 查漏补缺
        for (int i = 0; i <list.size() ; i++) {
            QuotationDayAveragePrice pice = list.get(i);
            Date currentDate = null;
            try {
                currentDate = df.parse(df.format(pice.getDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //比较当前日期和标记日期
            if (tempDate.before(currentDate)){
                List<String> beforeList = getDays(df.format(tempDate),df.format(currentDate));
                for (String beforeStr:beforeList) {
                    if (beforeStr.equals(df.format(pice.getDate()))){
                        HashMap<String, Object> resultMap = new HashMap<>();
                        resultMap.put("date",df.format(currentDate));
                        resultMap.put("avaPrice",pice.getDayAveragePrice());
                        resList.add(resultMap);
                    }else{
                        HashMap<String, Object> resultMap1 = new HashMap<>();
                        resultMap1.put("date",beforeStr);
                        resultMap1.put("avaPrice","0");
                        resList.add(resultMap1);
                    }

                }

            }else {
                HashMap<String, Object> resultMap1 = new HashMap<>();
                resultMap1.put("date",df.format(currentDate));
                resultMap1.put("avaPrice",pice.getDayAveragePrice());
                resList.add(resultMap1);
            }
            //比较完成，替换标记日期为 当前日期的后一天
            Date nextDay = null;
            try {
                nextDay = df.parse(df.format(currentDate));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar c = Calendar.getInstance();
            c.setTime(nextDay);
            int day1 = c.get(Calendar.DATE);
            c.set(Calendar.DATE, day1 + 1);
            tempDate = c.getTime();

            //补最后一条sql数据后的空日期数据
            if ((list.size() - 1) == i){
                if (currentDate.before(nowDate)){
                    List<String> beforeList = getDays(df.format(currentDate),df.format(nowDate));
                    for (String beforeStr:beforeList) {
                        if (!beforeStr.equals(df.format(currentDate))) {
                            HashMap<String, Object> resultMap1 = new HashMap<>();
                            resultMap1.put("date",beforeStr);
                            resultMap1.put("avaPrice","0");
                            resList.add(resultMap1);
                        }
                    }

                }
            }
        }

        double highestPrice = 0;
        double lowestPrice = 0;
        double avePrice = 0;
        double totlePrice = 0;
        for (Object subMap: resList) {
            HashMap<String, Object> temp = (HashMap<String, Object>) subMap;
            double tempPrice = Double.valueOf((String) temp.get("avaPrice"));
            if (tempPrice > highestPrice){
                highestPrice = tempPrice;
            }
            if (tempPrice < lowestPrice){
                lowestPrice = tempPrice;
            }
            totlePrice += tempPrice;
        }
        avePrice = totlePrice / resList.size();

        HashMap<String, Object> quotationMap = new HashMap<>();
        quotationMap.put("quotationList",resList);
        quotationMap.put("avePrice", avePrice);
        quotationMap.put("highestPrice", highestPrice);
        quotationMap.put("lowestPrice", lowestPrice);
        map.put("data", quotationMap);

        return R.ok(map);
    }

}
